package com.yicong.ants.ui.scenic;

import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.ui.adapter.StatefulBindMultiQuickAdapter;
import com.kennyc.view.MultiStateView;
import com.yicong.ants.BR;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.home.ScenicItemWrapper;
import com.yicong.ants.bean.scenic.CityItemBean;
import com.yicong.ants.bean.scenic.ScenicItem;
import com.yicong.ants.databinding.ScenicListActivityBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * type 1：黄金版；2：豪华版 ；4：免预约, 5: 特惠景区
 * 豪华版、黄金版风景区
 *
 * @author cchao
 */
public class ScenicListActivity extends BaseTitleBarActivity<ScenicListActivityBinding> implements View.OnClickListener {
    TextView drawTxt;
    EditText editSearch;
    StatefulBindMultiQuickAdapter<ScenicItemWrapper> mAdapter;
    /**
     * 景区类型
     */
    String mScenicType;
    private String city_id;
    /**
     * 搜索关键字
     */
    private String search_name;
    /**
     * 城市选择器
     */
    private OptionsPickerView pvCustomOptions;

    @Override
    protected int getLayout() {
        return R.layout.scenic_list_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleBarVisible(false);
        AppHelper.transStatus(getWindow());

        mScenicType = getIntent().getStringExtra(Constants.Extra.Scenic_Type);
        mDataBind.setClick(this);
        setTitleText(BusinessHelper.getScenicType(mScenicType));
        initViews();
        initAdapter();
        onLoadData();
    }

    //在合适的时机，释放广告的资源
    @Override
    protected void onDestroy() {
        super.onDestroy();
/*            if (mTTAd != null) {
                //调用destroy()方法释放
                mTTAd.destroy();
            }*/
    }

    private void initAdapter() {
        mDataBind.recycler.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new StatefulBindMultiQuickAdapter<ScenicItemWrapper>(null) {

            @Override
            public Map<Integer, Integer> getTypeLayoutMap() {
                Map<Integer, Integer> map = new HashMap<>(8);
                map.put(0, R.layout.scenic_item);
                return map;
            }

            @Override
            protected void convert(DataBindViewHolder helper, ScenicItemWrapper data) {
                convertScenic(helper, (ScenicItem) data.getObject());
            }

            @Override
            public void loadPageData(int page) {
                loadPage(page);
            }

            private void convertScenic(DataBindViewHolder helper, ScenicItem item) {
                helper.getBinding().setVariable(BR.bean, item);
//                helper.setText(R.id.scenic_type, BusinessHelper.getScenicTypeExplain(mScenicType));
//                helper.setImageDrawable(R.id.level_label, UiHelper.getDrawable(BusinessHelper.ScenicLabelMap.get(mScenicType)));

                helper.setVisible(R.id.limit_text, false);
                switch (item.getScenic_type()) {
                    case "10":
                    case "20":
                        helper.setText(R.id.limit_text, "一年限一次");
                        helper.setVisible(R.id.limit_text, true);
                        break;
                    case "30":
                        helper.setText(R.id.limit_text, "不限次");
                        helper.setVisible(R.id.limit_text, true);
                        break;
                }
            }
        };
        mAdapter.bindToRecyclerView(mDataBind.recycler);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (mAdapter.getData().get(position).getItemType() > 0) {
                return;
            }
            RouterHelper.toScenicDetail(thisActivity, ((ScenicItem) mAdapter.getData().get(position).getObject()).getScenic_id());
        });
    }

    @Override
    protected void onLoadData() {
        if (AmapHelper.hasLocationInfo()) {
            loadPage(1);
        } else {
            showToast("请开启定位获取准确位置");
            loadPage(1);
//            MapLocationUtils.checkLocation(aMapLocation -> loadPage(1));
        }
    }

    private void loadPage(final int page) {
        final Map<String, String> params = new HashMap<>();
        params.put("scenic_type", mScenicType);
        if (null != city_id) {
            params.put("city_id", city_id);
        }
        if (null != search_name) {
            params.put("search_name", search_name);
        }
        params.put("page", String.valueOf(page));

        if (page == 1) {
            mAdapter.setViewState(MultiStateView.VIEW_STATE_LOADING);
        }
        addSubscribe(RetrofitHelper.getApis().getScenicList(params)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        mAdapter.loadMoreComplete();
                    }
//                onLoadAd(page);

                    // 包装数据
                    List<ScenicItem> data = respBean.getList();
                    List<ScenicItemWrapper> list = new ArrayList<>();
                    for (ScenicItem datum : data) {
                        list.add(ScenicItemWrapper.of(0, datum));
                    }
                    mAdapter.solvePageData(list, page, respBean.getPageInfo().getCountPage());
                }, RxHelper.getSwitchableErrorConsumer(mAdapter)));
    }

    private void initCustomOptionPicker(final List<CityItemBean> data) {
        //条件选择器初始化，自定义布局
        /**
         * @description
         * 注意事项：
         * 自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
         * 具体可参考demo 里面的两个自定义layout布局。
         */
        pvCustomOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v) -> {
            //返回的分别是三个级别的选中位置
            city_id = data.get(options1).getCity_id();
            drawTxt.setText(data.get(options1).getName());
            initCityTxt(false);
            loadPage(1);
        }).setOutSideCancelable(false)
                .setLayoutRes(R.layout.pickerview_custom_options, v -> {
                    TextView tvSubmit = v.findViewById(R.id.tv_finish);
                    ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                    tvSubmit.setOnClickListener(v1 -> {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    });
                    ivCancel.setOnClickListener(v12 -> {
                        pvCustomOptions.dismiss();
                        initCityTxt(false);
                    });
                }).build();

        pvCustomOptions.setPicker(data);
    }

    protected void initViews() {
        editSearch = mDataBind.editSearch;
        drawTxt = mDataBind.drawTxt;

        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (StringUtils.isNull(editSearch.getText().toString())) {
                    search_name = null;
                }
            }
        });
        editSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                initSearch();
            }
            return false;
        });
    }

    private void initSearch() {
        if (StringUtils.isNull(editSearch.getText().toString())) {
            showToast("请输入关键字");
            return;
        }
        search_name = editSearch.getText().toString();
        loadPage(1);
    }

    /**
     * 更新textView背景
     *
     * @param tag
     */
    private void initCityTxt(boolean tag) {
        Logs.e("initCityTxt", "" + tag);
        int h = UiHelper.dp2px(10);
        int w = UiHelper.dp2px(14);
        if (tag) {
            Drawable drawable = getResources().getDrawable(R.drawable.icon_triangle_top);
            drawable.setBounds(0, 0, w, h);
            drawTxt.setCompoundDrawables(null, null, drawable, null);
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.icon_triangle_bot);
            drawable.setBounds(0, 0, w, h);
            drawTxt.setCompoundDrawables(null, null, drawable, null);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.rel_search:
                initSearch();
                break;
            case R.id.draw_txt:
                showProgress();
                addSubscribe(RetrofitHelper.getApis().city_list(Collections.emptyMap())
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            hideProgress();
                            if (respBean.isCodeFail()) {
                                showToast(respBean.getMsg());
                                return;
                            }
                            List<CityItemBean> list = CollectionHelper.isEmpty(respBean.getData()) ? new ArrayList<>() : respBean.getData();
                            CityItemBean bean = new CityItemBean();
                            bean.setCity_id(null);
                            bean.setName("全国");
                            list.add(0, bean);
                            initCustomOptionPicker(list);
                            pvCustomOptions.show();
                            initCityTxt(true);
                        }, RxHelper.getHideProgressConsumer(this)));
                break;
            case R.id.info:
                ZzConfigs.toWebActivityByUrlNotLogin(mContext, "ant_rule_coin");
                break;
        }
    }
}
